package gosu;

import java.io.File;
import java.nio.ByteBuffer;
import static gosu.Gosu.fmodCheck;
import static gosu.Gosu.FMOD;

import org.jouvieje.FmodEx.Sound;
import org.jouvieje.FmodEx.Channel;
import static org.jouvieje.FmodEx.Defines.FMOD_MODE.*;
import static org.jouvieje.FmodEx.Enumerations.FMOD_CHANNELINDEX.*;
import org.jouvieje.FmodEx.Structures.FMOD_CREATESOUNDEXINFO;


public class Sample {
  private Sound _sound;
  private Window _window;

  public Sample(Window window, String filename) {
    _window = window;
    _sound = new Sound();

    // Make sure FMOD is initialized
    Gosu.checkFmodInit();

    ByteBuffer buffer = Gosu.loadFileIntoMemory(filename);
    FMOD_CREATESOUNDEXINFO exinfo = FMOD_CREATESOUNDEXINFO.create();
    exinfo.setLength(buffer.capacity());
    fmodCheck(FMOD.createSound(buffer, FMOD_HARDWARE | FMOD_OPENMEMORY, exinfo, _sound));
    exinfo.release();
  }


  public SampleInstance play() {
    Channel channel = new Channel();
    fmodCheck(FMOD.playSound(FMOD_CHANNEL_FREE, _sound, false, channel));
    FMOD.update(); // garbage collection of channels or something?

    return new SampleInstance(channel);
  }


  public SampleInstance play(float volume) {
    SampleInstance si = play();
    si.setVolume(volume);
    return si;
  }


  public SampleInstance play(float volume, float speed) {
    SampleInstance si = play();
    si.setVolume(volume);
    si.setSpeed(speed);
    return si;
  }


  public SampleInstance playPan(float pan) {
    SampleInstance si = play();
    si.setPan(pan);
    return si;
  }


  public SampleInstance playPan(float pan, float volume) {
    SampleInstance si = play();
    si.setPan(pan);
    si.setVolume(volume);
    return si;
  }


  public SampleInstance playPan(float pan, float volume, float speed) {
    SampleInstance si = play();
    si.setPan(pan);
    si.setVolume(volume);
    si.setSpeed(speed);
    return si;
  }


  protected void finalize() {
    _sound.release();
  }
}
